﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Security;
using System.Security.Cryptography;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.TenPayLibV3;
using Senparc.Weixin.MP.AdvancedAPIs.QrCode;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlatWL.Data;
using System.Threading.Tasks;
using System.IO;

namespace PlatWL.Services.Tools
{
    public class WXHelp
    {
        public static string appid = "";
        public static string secret = "";
        public static string mchid = "";
        public static string mchidkey = "";
        public static string tenpayv3notify = "";

        static WXHelp()
        {
            appid = ConfigurationManager.AppSettings["wxappid"].ToString();
            secret = ConfigurationManager.AppSettings["wxappsecret"].ToString();
            mchid = ConfigurationManager.AppSettings["wxmchid"].ToString();
            mchidkey = ConfigurationManager.AppSettings["wxmchidkey"].ToString();
            tenpayv3notify = ConfigurationManager.AppSettings["tenpayv3notify"].ToString();
        }

        //注册微信API
        public static void RegisterWx()
        {
            AccessTokenContainer.Register(appid, secret);
            JsApiTicketContainer.Register(appid, secret);
        }
        public static string GetTicket()
        {
            return JsApiTicketContainer.GetJsApiTicket(WXHelp.appid);
        }
        public static string GetAccessToken()
        {
            return AccessTokenContainer.GetAccessToken(WXHelp.appid);
        }

        public static OAuthUserInfo GetUserInfoByCode(string code)
        {
            OAuthAccessTokenResult token = OAuthApi.GetAccessToken(WXHelp.appid, WXHelp.secret, code);

            OAuthUserInfo user = OAuthApi.GetUserInfo(token.access_token, token.openid);

            return user;
        }
        public static bool ISSubscribe(string openid)
        {
            try
            {
                WeixinUserInfoResult wx = CommonApi.GetUserInfo(WXHelp.GetAccessToken(), openid);
                if (wx.subscribe == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {

                string ss = ex.Message;
                return false;
            }
        }

        public static WeixinUserInfoResult GetUserInfo(string openid)
        {
            try
            {
                WeixinUserInfoResult wx = CommonApi.GetUserInfo(WXHelp.GetAccessToken(), openid);
                return wx;
            }
            catch (Exception ex)
            {

                string ss = ex.Message;
                return null;
            }
        }

        public static void SendTemplateMsg(string openid, string templateid, string url, object data)
        {
            try
            {
                switch (templateid)
                {
                    //新鉴定请求提醒
                    //{ { first.DATA} }
                    //鉴定内容：{ { keyword1.DATA} }
                    //提交时间：{ { keyword2.DATA} }
                    //{ { remark.DATA} }
                    case "jiandingtixing":
                        {
                            templateid = "vgIfUHJy6QgivI_EAxvWbj1yaXDQ3rvRaHyLmnzVRUI";
                        }
                        break;

                    //鉴定结果通知
                    //{ { first.DATA} }
                    //鉴定结果：{ { keyword1.DATA} }
                    //鉴定时间：{ { keyword2.DATA} }
                    //{ { remark.DATA} }
                    case "jiandingjieguo":
                        {
                            templateid = "SZ3l7B9ggVajAL2zC2cs9eq5QnTet0Vh8rTho239suk";
                        }
                        break;
                }
                Task.Factory.StartNew(async () =>
                {
                    string access_token = WXHelp.GetAccessToken();
                    var result = await TemplateApi.SendTemplateMessageAsync(access_token, openid, templateid, url, data);
                });

            }
            catch { }
        }


        public static string SendRedPack(pt_user_account user, int cjID)
        {
            string strmsg = "";
            //try
            //{
            //    if (user == null || string.IsNullOrWhiteSpace(user.OpenID))
            //    {
            //        return "用户不存在或没有绑定微信";
            //    }
            //    var cj = new PT_Activity_PrizeRecordB().GetEntity(d => d.ID == cjID);
            //    if (cj == null || cj.ISRed != 1 || cj.RedMoney == null)
            //    {
            //        return "非红包类奖品";
            //    }
            //    var hd = new PT_Activity_HDGLB().GetEntity(d => d.ID == cj.HDType);

            //    //CerPath证书路径
            //    string certPath = ConfigurationManager.AppSettings["certPath"].ToString();
            //    //证书密码
            //    //string password = ConfigurationManager.AppSettings["password"].ToString();

            //    string nonceStr = "", paySign = "";

            //    int m = (int)(cj.RedMoney * 100);
            //    if (m >= 100)
            //    {
            //        var result = RedPackApi.SendNormalRedPack(
            //            appid,
            //            mchid,
            //            mchidkey,
            //            certPath,
            //            user.OpenID,
            //            "芝麻校园",    //红包发送者名称，会显示给接收红包的用户
            //            "60.205.6.98",         //IP发送红包的服务器地址
            //            m,          //红包金额（单位分）
            //            "欢迎关注“芝麻校园”,获取最新校园信息",         //祝福语
            //            hd.Title,   //活动名称
            //            "",         //活动描述，用于低版本微信显示
            //            out nonceStr,
            //            out paySign);
            //        if (result.result_code)
            //        {
            //            Common.CommonClass.WriteLog("3");
            //            var red = new pt_activity_redpack();
            //            red.err_code = result.err_code;
            //            red.err_code_des = result.err_code_des;
            //            red.mch_billno = result.mch_billno;
            //            red.mch_id = result.mch_id;
            //            red.nonceStr = nonceStr;
            //            red.paySign = paySign;
            //            red.result_code = result.result_code ? "1" : "0";
            //            red.return_code = result.return_code ? "1" : "0";
            //            red.return_msg = result.return_msg;
            //            red.re_openid = result.re_openid;
            //            red.send_listid = result.send_listid;
            //            red.send_time = result.send_time;
            //            red.total_amount = result.total_amount;
            //            red.wxappid = result.wxappid;
            //            red.CRTime = DateTime.Now;
            //            new PT_Activity_RedPackB().Insert(red);
            //            string sql = string.Format("UPDATE PT_Activity_PrizeRecord SET RedPackOrderID='{0}' WHERE ID={1} ", red.mch_billno, cjID);
            //            new PT_Activity_PrizeRecordB().ExsSql(sql);
            //            return "红包发送成功";
            //        }
            //        else
            //        {
            //            Common.CommonClass.WriteLog(result.err_code + result.err_code_des);
            //            //Tools.Common.WriteLog("异常", "", JsonConvert.SerializeObject(result));
            //            return "红包发送失败";
            //        }
            //    }
            //    else
            //    {
            //        //Tools.Common.WriteLog("异常", "", JsonConvert.SerializeObject(cj));
            //        return "金额有误,红包发送失败";
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Common.CommonClass.WriteLog(ex.Message);
            //    strmsg = "红包发送失败";
            //}
            return strmsg;
        }

        public static string GetQrCode(int senceid)
        {
            string access_token = WXHelp.GetAccessToken();
            CreateQrCodeResult r = QrCodeApi.Create(access_token, 2592000, senceid, QrCode_ActionName.QR_LIMIT_STR_SCENE);
            string qrcode = QrCodeApi.GetShowQrCodeUrl(r.ticket);

            return qrcode;
        }

        public static bool checkSignature(string signature,string timestamp,string nonce)
        {

            return CheckSignature.Check(signature, timestamp, nonce, "shequhaoshenghuogood111");

        }


        /// <summary>
        /// JSAPI权限验证
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static object JSSDKGETSIGNAGURE(string url)
        {
            try
            {
                string jsapi_ticket = WXHelp.GetTicket();

                string noncestr = CreatenNonce_str();
                long timestamp = CreatenTimestamp();

                var string1Builder = new StringBuilder();
                string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                              .Append("noncestr=").Append(noncestr).Append("&")
                              .Append("timestamp=").Append(timestamp).Append("&")
                              .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
                string string1 = string1Builder.ToString();

                byte[] StrRes = Encoding.Default.GetBytes(string1);
                HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
                StrRes = iSHA.ComputeHash(StrRes);
                StringBuilder EnText = new StringBuilder();
                foreach (byte iByte in StrRes)
                {
                    EnText.AppendFormat("{0:x2}", iByte);
                }

                //Tools.Common.WriteLog(url);
                //Tools.Common.WriteLog(jsapi_ticket);

                var jsobj = new JObject(
                         new JProperty("appId", appid),
                         new JProperty("noncestr", noncestr),
                         new JProperty("timestamp", timestamp),
                         new JProperty("signature", EnText.ToString())
                         );

                //Tools.Common.WriteLog(JsonConvert.SerializeObject(jsobj));
                return jsobj;

            }
            catch (Exception ex) { Tools.Common.WriteLog(ex.Message + " " + ex.InnerException.Message); }
            return null;
        }

        /// <summary>
        /// 生成随即字符串
        /// </summary>
        /// <returns></returns>
        private static string CreatenNonce_str()
        {
            string[] strs = new string[]
                                 {
                                  "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                                  "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                                 };
            Random r = new Random();
            var sb = new StringBuilder();
            var length = strs.Length;
            for (int i = 0; i < 15; i++)
            {
                sb.Append(strs[r.Next(length - 1)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 创建时间戳
        /// </summary>
        /// <returns></returns>
        private static long CreatenTimestamp()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }




        public static string DownMediaFile(string serverId)
        {
            string lg = HttpContext.Current.Server.MapPath("/LOG/");
            string ids = "";

            foreach (var mediaId in serverId.Split(','))
            {
                string ff = MediaApi.Get(WXHelp.GetAccessToken(), mediaId, lg);

                string md5 = Tools.Common.HttpPostFile("http://60.205.6.98:9000/v2/tx/document/fileupload", ff);
                if (md5 != "")
                {

                    System.IO.FileInfo f = new FileInfo(ff);
                    pt_base_file newfile = new pt_base_file();
                    newfile.Name = f.Name;
                    newfile.FileMD5 = md5.Replace("\"", "");
                    newfile.FileSize = f.Length.ToString();
                    newfile.FileVersin = 0;
                    newfile.CRDate = DateTime.Now;
                    // newfile.CRUser = UserInfo.User.UserName;
                    newfile.UPDDate = DateTime.Now;
                    //newfile.UPUser = UserInfo.User.UserName;
                    newfile.FolderID = 3;
                    newfile.FileExtendName = f.Extension.Substring(1);
                    newfile.ISYL = "Y";

                    new pt_base_fileb().Insert(newfile);

                    if (ids == "")
                    {
                        ids = newfile.ID.ToString();
                    }
                    else
                    {
                        ids += "," + newfile.ID.ToString();
                    }


                    File.Delete(ff);
                }

            }
                
            return ids;

        }

    }



}

